<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\AuthorizationRequest;
use App\Http\Requests\Api\SocialAuthorizationRequest;

use App\Http\Requests\Api\WeappAuthorizationRequest;
use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Overtrue\LaravelSocialite\Socialite;

class AuthorizationsController extends Controller {
    //微信登录
    public function socialStore(SocialAuthorizationRequest $request, $type) {
       $driver = Socialite::create($type);
        try {
            if($code = $request->code){
                $oauthUser = $driver->userFromCode($code);
            }else{
                if($type == 'wechat'){
                    $driver->withOpenid($request->openid);
                }
                $oauthUser = $driver->userFromToken($request->access_token);
            }
        }catch (\Exception $e){
            throw new AuthenticationException('未知错误，获取用户信息失败');
        }
        if(!$oauthUser->getId()){
            throw new AuthenticationException('未知错误，获取用户唯一标识失败');
        }
        switch ($type){
            case 'wechat':
                $unionid = $oauthUser->getRaw()['unionid'] ?? null;
                if($unionid){
                    $user = User::where('weixin_unionid',$unionid)->first();
                }else{
                    $user = User::where('weixin_openid',$oauthUser->getId())->first();
                }
                if(!$user){
                    User::create([
                        'name'=>$oauthUser->getNickname(),
                        'avatar'=>$oauthUser->getAvatar(),
                        'weixin_openid'=>$oauthUser->getId(),
                        'unionid'=>$unionid
                    ]);
                }
                break;
        }
        $token = auth('api')->login($user);
        return $this->responseWithToken($token)->setStatusCode(201);
    }

    //普通登录
    public function store(AuthorizationRequest $request){
        $username = $request->username;
        $data = [];
        filter_var($username,FILTER_VALIDATE_EMAIL) ?
            $data['email'] = $username :
            $data['phone'] = $username;
        $data['password'] = $request->password;

        if(!$token = Auth::guard('api')->attempt($data)){
            throw new AuthenticationException(trans('auth.failed'));
        }
        return $this->responseWithToken($token)->setStatusCode(201);
    }

    //小程序的登录或绑定邮箱手机
    public function weappStore(WeappAuthorizationRequest $request){
        $data = getWeappData($request->code);
        if(isset($data['error'])){
            throw new AuthorizationException('未知错误');
        }
        $user = User::where('weapp_openid',$data['openid'])->first();
        $updateData['weixin_session_key'] = $data['session_key'];
        if(!$user){
            if(!$request->username){
                throw new AuthorizationException('请输入需绑定的手机或邮箱');
            }
            $username = $request->username;
            filter_var($username,FILTER_VALIDATE_EMAIL) ?
                $authData['email'] = $username :
                $authData['phone'] = $username;
            $authData['password'] = $request->password;
            if(!auth('api')->once($authData)){
                throw new AuthorizationException('账号或密码错误');
            }
            $user = auth('api')->getUser();
            $updateData['weapp_openid'] = $data['openid'];
        }
        $user->update($updateData);
        $token = auth('api')->login($user);
        return $this->responseWithToken($token)->setStatusCode(201);
    }
    //刷新令牌
    public function update() {
        $token = auth('api')->refresh();
        return $this->respondWithToken($token);
    }
    public function destroy() {
        auth('api')->logout();
        return response(null, 204);
    }

}
